// pages/myself/order/NewOrder.js
var Zan = require('../../../dist/index.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
var start00 = 0;
var start01 = 0;
var start02 = 0;
var start03 = 0;
var start04 = 0;

Page(Object.assign({}, Zan.Tab, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    tab: {
      list: [{
        id: 1,
        title: '全部'
      }, {
        id: 2,
        title: '待付款'
      }, {
        id: 3,
        title: '自取'
      }, {
        id: 4,
        title: '送货'
      }, {
        id: 5,
        title: '已完成'
      }],
      selectedId: 0,
      height: 45,
      scroll: false
    },
    delOrderId: "",
    endOrderId: "",
    scanOrderId: "",
    allOrder: [],
    order01: [],
    order02: [],
    order03: [],
    order04: [],
    activeIndex: 0,
    recordsTotal00: 0,
    recordsTotal01: 0,
    recordsTotal02: 0,
    recordsTotal03: 0,
    recordsTotal04: 0,
    hideStatus: true,
    nodata: {
      msg: '无相关数据',
      notype: 1,
      imgurl: '../../../images/nodatas.png',
      nourl: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    wx.setNavigationBarTitle({
      title: "商城订单",
    })
    this.data.tab.selectedId = options.index;
    this.setData({
      tab: this.data.tab,
    })
    this.setData({
      activeIndex: options.index
    })
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    /**
     * type: 0线上
     * type: 1线下
     */
    if (this.data.tab.selectedId == 1) {
      start00 = 0;
      this.setData({
        allOrder: [],
      });
      network._post_page_json(this, api.getOrderList, start00, { queryType: this.data.tab.selectedId }, success00);
    } else if (this.data.tab.selectedId == 2) {
      start01 = 0;
      this.setData({
        order01: [],
      });
      network._post_page_json(this, api.getOrderList, start01, { queryType: this.data.tab.selectedId }, success01);
    } else if (this.data.tab.selectedId == 3) {
      start02 = 0;
      this.setData({
        order02: [],
      });
      network._post_page_json(this, api.getOrderList, start02, { queryType: this.data.tab.selectedId }, success02);
    } else if (this.data.tab.selectedId == 4) {
      start03 = 0;
      this.setData({
        order03: [],
      });
      network._post_page_json(this, api.getOrderList, start03, { queryType: this.data.tab.selectedId }, success03);
    } else if (this.data.tab.selectedId == 5) {
      start04 = 0;
      this.setData({
        order04: [],
      });
      network._post_page_json(this, api.getOrderList, start04, { queryType: this.data.tab.selectedId }, success04);
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.tab.selectedId == 1) {
      if (this.data.allOrder.length < this.data.recordsTotal00) {
        start00 = start00 + 20;
        network._post_page_json(this, api.getOrderList, start00, { queryType: this.data.tab.selectedId }, success00);
      }
    } else if (this.data.tab.selectedId == 2) {
      if (this.data.order01.length < this.data.recordsTotal01) {
        start01 = start01 + 20;
        network._post_page_json(this, api.getOrderList, start01, { queryType: this.data.tab.selectedId }, success01);
      }
    } else if (this.data.tab.selectedId == 3) {
      if (this.data.order02.length < this.data.recordsTotal02) {
        start02 = start02 + 20;
        network._post_page_json(this, api.getOrderList, start02, { queryType: this.data.tab.selectedId }, success02);
      }
    } else if (this.data.tab.selectedId == 4) {
      if (this.data.order03.length < this.data.recordsTotal03) {
        start03 = start03 + 20;
        network._post_page_json(this, api.getOrderList, start03, { queryType: this.data.tab.selectedId }, success03);
      }
    } else if (this.data.tab.selectedId == 5) {
      if (this.data.order04.length < this.data.recordsTotal04) {
        start04 = start04 + 20;
        network._post_page_json(this, api.getOrderList, start04, { queryType: this.data.tab.selectedId }, success04);
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  handleZanTabChange(e) {
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      [`${componentId}.selectedId`]: selectedId
    });


    this.setData({
      activeIndex: selectedId
    })

    if (this.data.tab.selectedId == 1) {
      start00 = 0;
      this.setData({
        allOrder: [],
      });
      network._post_page_json(this, api.getOrderList, start00, { queryType: this.data.tab.selectedId }, success00);
    } else if (this.data.tab.selectedId == 2) {
      start01 = 0;
      this.setData({
        order01: [],
      });
      network._post_page_json(this, api.getOrderList, start01, { queryType: this.data.tab.selectedId }, success01);
    } else if (this.data.tab.selectedId == 3) {
      start02 = 0;
      this.setData({
        order02: [],
      });
      network._post_page_json(this, api.getOrderList, start02, { queryType: this.data.tab.selectedId }, success02);
    } else if (this.data.tab.selectedId == 4) {
      start03 = 0;
      this.setData({
        order03: [],
      });
      network._post_page_json(this, api.getOrderList, start03, { queryType: this.data.tab.selectedId }, success03);
    } else if (this.data.tab.selectedId == 5) {
      start04 = 0;
      this.setData({
        order04: [],
      });
      network._post_page_json(this, api.getOrderList, start04, { queryType: this.data.tab.selectedId }, success04);
    }
  },

  // 取消订单
  cancel: function (e) {
    var orderId = e.currentTarget.dataset.id;
    this.setData({
      delOrderId: orderId
    })
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定删除该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { orderId: orderId }, success);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 确认收货
  endOrder: function (e) {
    var orderId = e.currentTarget.dataset.id;
    this.setData({
      endOrderId: orderId
    })
    network._post_json(this, api.endOrder, { orderId: orderId }, endSuccess);
  },

  // 购买
  pay: function (e) {
    var item = e.currentTarget.dataset.item;
    var againPay = e.currentTarget.dataset.again; // 再次购标记
    var products = item.product;
    var address = item.address;
    var liuyan = item.content;
    var newProducts = [];
    for (var i = 0; i < products.length; i++) {
      var product = {};
      product.id = products[i].id;
      product.title = products[i].title;
      product.smallImgUrl = products[i].smallImgUrl;
      product.count = products[i].count;
      product.commodityActivity = products[i].commodityActivity;
      if (products[i].productSpec) {
        if (products[i].productSpec.name && !products[i].productSpec.name1 && !products[i].productSpec.name2){
          var specName = products[i].productSpec.name
        } else if (products[i].productSpec.name1 && !products[i].productSpec.name2){
          var specName = products[i].productSpec.name + '+' + products[i].productSpec.name1
        } else if (products[i].productSpec.name2){
          var specName = products[i].productSpec.name + '+' + products[i].productSpec.name1 + '+' + products[i].productSpec.name2
        }
        product.price = products[i].productSpec.price;
        product.specId = products[i].productSpec.id;
        product.specName = specName;
        product.count = products[i].count;
      } else {
        product.price = products[i].price;
      }
      newProducts.push(product);
    }
    try {
      wx.setStorageSync('products', newProducts)
    } catch (e) {
    }
    if (item.customStoreId) {
      wx.navigateTo({
        url: '/pages/pay/Pay?orderId=' + item.id + '&orderNO=' + item.orderNO + '&orderDesc=' + item.orderDesc + '&address=' + JSON.stringify(address) + '&liuyan=' + liuyan + '&againPay=' + againPay + '&storeId=' + item.customStoreId
      })
    } else {
      wx.navigateTo({
        url: '/pages/pay/Pay?orderId=' + item.id + '&orderNO=' + item.orderNO + '&orderDesc=' + item.orderDesc + '&address=' + JSON.stringify(address) + '&liuyan=' + liuyan + '&againPay=' + againPay
      })
    }

  },

  //扫码自取
  scan: function (e) {
    var orderId = e.currentTarget.dataset.orderid;

    this.setData({
      scanOrderId: orderId
    })
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var scene = decodeURIComponent(res.path);
        var index = scene.indexOf('scene=s=')
        // app.globalData.storeId == scene.substring(2, scene.length);
        network._post_json(this, api.end, { orderId: orderId, storeId: scene.substring(index + 8, scene.length) }, scanSuccess);
      }
    })
  },
  /**
  * 拨打电话
  */
  call: function (e) {
    /**
    * 获取商家电话
    */
    if (app.globalData.userAndTenantInfo) {
      wx.makePhoneCall({
        phoneNumber: app.globalData.userAndTenantInfo.tenant.phone
      })
    } else {
      app.userAndTenantInfoCallback = res => {
        this.setData({
          tenant: res.tenant
        })
      }
    }
  },
  //售后
  shouhouTk: function (e) {
    order.shouhouTk(0, e);

  },

  //售后处理
  Agreeaftersale: function (e) {
    var order = e.currentTarget.dataset.order;
    if (order.product[0].productSpec) {
      var productprice = order.product[0].productSpec.price;
      var pspec = order.product[0].productSpec.name
    } else {
      var productprice = order.product[0].price
    }
    var saleMoney = order.oldSaleMoney;
    var integralPrice = order.oldIntegralPrice;
    var ordertotal = order.oldTotal + saleMoney + integralPrice;
    var refund_fee = order.product[0].refundOrder.refund_fee;
    if (order.product[0].applicationBack.type == 1) {
      var ordertype = '已经发货'
    } else {
      var ordertype = '未发货'
    }
    if (order.product[0].refundOrder.status == 0) {
      var Refundresults = '同意退款'
    } else if (order.product[0].refundOrder.status == 1) {
      var Refundresults = '拒绝售后，请联系商家'
    } else if (order.product[0].refundOrder.status == 2) {
      var Refundresults = '退款成功'
    } else if (order.product[0].refundOrder.status == 4) {
      var Refundresults = '正在处理售后，请等待'
    }
    var createDate = utils.formatDate(new Date(order.product[0].refundOrder.createDate));
    if (order.product[0].refundOrder.endDate != null) {
      var endDate = utils.formatDate(new Date(order.product[0].refundOrder.endDate));
    } else {
      var endDate = order.product[0].refundOrder.endDate
    }
    var getdata = {
      'productimg': order.product[0].smallImgUrl,
      'producttitle': order.product[0].title,
      'productspec': pspec,
      'productprice': productprice,
      'productcount': order.product[0].count,
      'agreeafterprice': refund_fee,
      'tuikuan': ordertype,
      'tuikuanwhy': order.product[0].applicationBack.reason,
      'tuikuancontent': order.product[0].applicationBack.refund_content,
      'tuikuanresults': Refundresults,
      'istongyi': order.product[0].refundOrder.status,
      'isfahuo': order.product[0].applicationBack.type,
      'tuihuoorderid': order.product[0].refundOrder.id,
      'expressName': order.product[0].refundOrder.expressName,
      'expressNo': order.product[0].refundOrder.expressNo,
      'createdate': createDate,
      'enddate': endDate,
      'out_refund_no': order.product[0].refundOrder.out_refund_no,
      'ordertotal': ordertotal,
      'maijialiu': order.product[0].refundOrder.content,
      'ordertype': order.type,
      'tyueyouhui': productprice * order.product[0].count - refund_fee
    }
    wx.setStorageSync('neworder', getdata)
    if (order.product[0].refundOrder.status == 0 || order.product[0].refundOrder.status == 4 || order.product[0].refundOrder.status == 1) {
      wx.navigateTo({
        url: '/pages/myself/order/shouhou/waitingSale',
      })
    } else if (order.product[0].refundOrder.status == 2) {
      wx.navigateTo({
        url: '/pages/myself/order/shouhou/refunded',
      })
    }

  },

  refresh: function () {
    this.onPullDownRefresh();
  }

}))

// 获取订单列表结果
var success00 = function (that, res) {
  for (var j = 0; j < res.data.data.length; j++) {
    var product = res.data.data[j].product;
    for (var i = 0; i < product.length; i++) {
      if (product[i].productSpec) {
        product[i].price = product[i].productSpec.price;
        product[i].specId = product[i].productSpec.id;
        product[i].specName = product[i].productSpec.name;
      }
    }
    res.data.data[j].product = product;
  }
  that.setData({
    allOrder: that.data.allOrder.concat(res.data.data),
    recordsTotal00: res.data.recordsTotal
  })
}

// 获取订单列表结果
var success01 = function (that, res) {
  for (var j = 0; j < res.data.data.length; j++) {
    var product = res.data.data[j].product;
    for (var i = 0; i < product.length; i++) {
      if (product[i].productSpec) {
        product[i].price = product[i].productSpec.price;
        product[i].specId = product[i].productSpec.id;
        product[i].specName = product[i].productSpec.name;
      }
    }
    res.data.data[j].product = product;
  }
  that.setData({
    order01: that.data.order01.concat(res.data.data),
    recordsTotal01: res.data.recordsTotal
  })

}

// 获取订单列表结果
var success02 = function (that, res) {
  for (var j = 0; j < res.data.data.length; j++) {
    var product = res.data.data[j].product;
    for (var i = 0; i < product.length; i++) {
      if (product[i].productSpec) {
        product[i].price = product[i].productSpec.price;
        product[i].specId = product[i].productSpec.id;
        product[i].specName = product[i].productSpec.name;
      }
    }
    res.data.data[j].product = product;
  }
  that.setData({
    order02: that.data.order02.concat(res.data.data),
    recordsTotal02: res.data.recordsTotal
  })

}

// 获取订单列表结果
var success03 = function (that, res) {
  for (var j = 0; j < res.data.data.length; j++) {
    var product = res.data.data[j].product;
    for (var i = 0; i < product.length; i++) {
      if (product[i].productSpec) {
        product[i].price = product[i].productSpec.price;
        product[i].specId = product[i].productSpec.id;
        product[i].specName = product[i].productSpec.name;
      }
    }
    res.data.data[j].product = product;
  }
  that.setData({
    order03: that.data.order03.concat(res.data.data),
    recordsTotal03: res.data.recordsTotal
  })

}

// 获取订单列表结果
var success04 = function (that, res) {
  for (var j = 0; j < res.data.data.length; j++) {
    var product = res.data.data[j].product;
    for (var i = 0; i < product.length; i++) {
      if (product[i].productSpec) {
        product[i].price = product[i].productSpec.price;
        product[i].specId = product[i].productSpec.id;
        product[i].specName = product[i].productSpec.name;
      }
    }
    res.data.data[j].product = product;
  }
  that.setData({
    order04: that.data.order04.concat(res.data.data),
    recordsTotal04: res.data.recordsTotal
  })
}

// 取消订单
var success = function (that, res) {
  if (that.data.tab.selectedId == 0) {
    that.setData({
      allOrder: Array.prototype.remove(that.data.allOrder, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 1) {
    that.setData({
      order01: Array.prototype.remove(that.data.order01, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 2) {
    that.setData({
      order02: Array.prototype.remove(that.data.order02, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 3) {
    that.setData({
      order03: Array.prototype.remove(that.data.order03, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 4) {
    that.setData({
      order04: Array.prototype.remove(that.data.order04, that.data.delOrderId)
    })
  }

  that.showZanToast('订单删除成功');
  that.onPullDownRefresh();
}

// 扫码自提
var scanSuccess = function (that, res) {
  if (that.data.tab.selectedId == 0) {
    that.setData({
      allOrder: Array.prototype.remove(that.data.allOrder, that.data.scanOrderId)
    })
  } else if (that.data.tab.selectedId == 1) {
    that.setData({
      order01: Array.prototype.remove(that.data.order01, that.data.scanOrderId)
    })
  } else if (that.data.tab.selectedId == 2) {
    that.setData({
      order02: Array.prototype.remove(that.data.order02, that.data.scanOrderId)
    })
  } else if (that.data.tab.selectedId == 3) {
    that.setData({
      order03: Array.prototype.remove(that.data.order03, that.data.scanOrderId)
    })
  } else if (that.data.tab.selectedId == 4) {
    that.setData({
      order04: Array.prototype.remove(that.data.order04, that.data.scanOrderId)
    })
  }

  that.showZanToast('自提成功');
  that.onPullDownRefresh();
}

var endSuccess = function (that, res) {
  that.onPullDownRefresh();
  //if (res.data.data) {
  that.setData({
    order03: Array.prototype.remove(that.data.order03, that.data.endOrderId)
  });
  that.showZanToast('收货成功');
  //}
}

Array.prototype.remove = function (order, id) {
  for (var i = 0; i < order.length; i++) {
    if (order[i].id == id) {
      order.splice(i, 1);
    }
  }
  return order;
}

var getCount = function (that, products) {
  let count = 0;
  for (let i = 0; i < products.length; i++) {
    count += products[i].count;
  }
  that.setData({
    count: count
  })
}